package com.zzl.bonds.ticket.controller.feign.plat;

import com.zzl.apidoc.annotation.ApidocController;
import com.zzl.apidoc.annotation.ApidocOperation;
import com.zzl.apidoc.annotation.ApidocParam;
import com.zzl.bonds.ticket.constant.status.HandStatusEnum;
import com.zzl.bonds.ticket.constant.type.TicketTypeEnum;
import com.zzl.bonds.ticket.dto.KeyValue;
import com.zzl.bonds.ticket.dto.finance.*;
import com.zzl.bonds.ticket.dto.ticketopen.CheckSubmit;
import com.zzl.bonds.ticket.service.SupplierCreditService;
import com.zzl.bonds.ticket.service.TicketFinanceService;
import com.zzl.general.common.apidoc.annotation.ApidocParamsPage;
import com.zzl.general.common.apidoc.annotation.ApidocResultKeyValR;
import com.zzl.general.common.apidoc.annotation.ApidocReturnPage;
import com.zzl.general.common.apidoc.annotation.ApidocReturnR;
import com.zzl.general.common.apidoc.constants.ResultTypeInR;
import com.zzl.general.common.ctrl.WebBaseCtrl;
import com.zzl.general.common.exception.SysException;
import com.zzl.general.common.utils.LogUtils;
import com.zzl.general.common.utils.PageUtils;
import com.zzl.general.common.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * ticket 服务 对外提供的 接口
 *
 * @author : gull
 * @date : 2022/3/9 14:22
 */
@ApidocController("给运营平台提供的 rpc 接口")
@RestController
@RequestMapping("bondsticket/feign")
@Slf4j
public class FinanceController extends WebBaseCtrl {
    @Autowired
    private TicketFinanceService ticketFinanceService;
    @Autowired
    private SupplierCreditService supplierCreditService;

    @GetMapping("/approveList")
    @ApidocOperation(description = "融资审核列表", operationId = "ticket/ticketfinance/approveList")
    @ApidocReturnPage(genericTypeClass = TicketFinanceListDto.class)
    public Result approveList(@ApidocParamsPage(name = "params",
            keyName = {
                    "ticketNo"
                    , "financeEnterpriseName"
                    , "startAmount"
                    , "endAmount"
                    , "financeInstitutyId"
                    , "startTime"
                    , "endTime"
                    , "page"
                    , "order"
            }
            , keyDescription = {
            "凭证编号"
            , "融资企业"
            , "开始金额"
            , "结 束金额"
            , "金融机构id "
            , "融单开始日期"
            , "融单结束日期"
            , "排序类型：create_time（默认）、sell_amount：融资本金、estimated_financing_interest：预计融资利息，" +
            "service_chage：预计服务费用,create_time:申请日期，cash_time：到期日期"
            , "排序方式：desc 降序（默认）asc 升序"})
                              @RequestParam Map<String, Object> params) {
        try {
            PageUtils page = ticketFinanceService.queryApproveFinancePage(params, this.getUser(), this.getSession());
            return Result.ok().put("page", page);
        } catch (SysException e) {
            e.printStackTrace();
            return Result.error(e.getMsg());
        }
    }

    @GetMapping("/info/{id}")
    @ApidocOperation(description = "融单审核详情", operationId = "/ticket/ticketfinance/feign/info-test")
    @ApidocReturnR(otherkv = {
            @ApidocResultKeyValR(resultType = ResultTypeInR.TYPE_OBJECT, key = "data", valueClass = TicketFinanceDto.class)
    })
    public Result getFinanceApproveDetail(@ApidocParam(name = "id", description = "融资id", required = true) @PathVariable("id") String id) {
        try {
            return Result.ok().put("data", ticketFinanceService.getFinanceApproveDetail(id, this.getUser()));
        } catch (SysException e) {
            return Result.error(e.getMsg());
        }
    }

    @GetMapping("/contractList")
    @ApidocOperation(description = "融单协议列表", operationId = "/ticket/ticketfinance/feign/contractList")
    @ApidocReturnR(otherkv = {
            @ApidocResultKeyValR(resultType = ResultTypeInR.TYPE_OBJECT, key = "data", valueClass = ContractTemplateDto.class)
    })
    public Result financeContract(@ApidocParamsPage(name = "params",
            keyName = {"contractName"}, keyDescription = {"协议名称"})
                                  @RequestParam Map<String, Object> params) {
        return Result.ok().put("data", ticketFinanceService.getFinanceContractList(params));
    }

    @PostMapping("/financeTicketApproveSubmit")
    @ApidocOperation(description = "融资，平台审核提交", operationId = "/ticket/ticketfinance/financeTicketApproveSubmit")
    @ApidocReturnR
    public Result financeTicketApproveSubmit(@ApidocParam(name = "平台审核提交", required = true) @Validated @RequestBody CheckSubmit checkSubmit) {
        try {
            ticketFinanceService.financeTicketApproveSubmit(checkSubmit, this.getUser());
            return Result.ok();
        } catch (SysException e) {
            return Result.error(e.getMsg());
        }
    }

    @GetMapping("/financeList")
    @ApidocOperation(description = "融资管理-融资列表", operationId = "ticket/ticketfinance/feign/financeList")
    @ApidocReturnPage(genericTypeClass = TicketFinanceListDto.class)
    public Result financeList(@ApidocParamsPage(name = "params",
            keyName = {
                    "ticketNo"
                    , "financeEnterpriseName"
                    , "handStatus"
                    , "page"
                    , "order"
            }
            , keyDescription = {
            "凭证编号"
            , "融资企业"
            , "处理状态，见接口与原型 依次 1,2,3,4,必传，默认全部 "
            , "排序类型：create_time（默认）、sell_amount：融资金额、estimated_financing_interest：预计融资利息，" +
            "service_chage：预计服务费用,create_time:融资申请日期，loan_time：实际放款日期"
            , "排序方式：desc 降序（默认）asc 升序"})
                              @RequestParam Map<String, Object> params) {
        try {
            PageUtils page = ticketFinanceService.queryPage(params, null);
            return Result.ok().put("page", page);
        } catch (SysException e) {
            e.printStackTrace();
            return Result.error(e.getMsg());
        }
    }

    @GetMapping("/financeDetail/{id}")
    @ApidocOperation(description = "融单管理详情", operationId = "/ticket/ticketfinance/feign/financeDetail")
    @ApidocReturnR(otherkv = {
            @ApidocResultKeyValR(resultType = ResultTypeInR.TYPE_OBJECT, key = "data", valueClass = TicketFinanceDetailDto.class)
    })
    public Result getFinanceDetail(@ApidocParam(name = "id", description = "融资id", required = true) @PathVariable("id") String id) {
        try {
            return Result.ok().put("data", ticketFinanceService.financeDetail(id, this.getUser()));
        } catch (SysException e) {
            return Result.error(e.getMsg());
        }
    }

    /**
     * 获取处理状态
     */
    @GetMapping("/handStatus")
    @ApidocOperation(description = "获取处理状态", operationId = "ticket/ticketfinance/feign/handStatus1")
    @ApidocReturnR
            (otherkv = {
                    @ApidocResultKeyValR(resultType = ResultTypeInR.TYPE_COLLOCTION, key = "list", genericTypeClass = KeyValue.class)
            })
    public Result approveStatus() {
        return Result.ok().put("list", HandStatusEnum.getKvList(TicketTypeEnum.TICKET_TYPE_FINANCE.getCode()));
    }

    /**
     * 修改
     */
    @PutMapping("/update")
    @ApidocOperation(description = "修改融资申请信息", operationId = "ticket/ticketfinance/feign/update")
    @ApidocReturnR
    public Result update(@ApidocParam(name = "修改融资申请信息", required = true) @RequestBody TicketFinanceUpdateDto financeUpdateDto) {
        try {
            ticketFinanceService.updateTicketFinanceById(financeUpdateDto, this.getUser());
            return Result.ok();
        } catch (SysException e) {
            LogUtils.logSysException(log, e);
            return Result.error(e.getMsg());
        }
    }

    @GetMapping("/financeStatus/{id}")
    @ApidocOperation(description = "获取业务状态", operationId = "ticket/ticketfinance/feign/handStatus2")
    @ApidocReturnR
            (otherkv = {
                    @ApidocResultKeyValR(resultType = ResultTypeInR.TYPE_COLLOCTION, key = "list", genericTypeClass = KeyValue.class)
            })
    public Result financeStatus(@ApidocParam(name = "id", description = "融资id", required = true) @PathVariable("id") String id) {

        return Result.ok().put("list", ticketFinanceService.financeStatus(id));
    }

    @PostMapping("/addFinanceCredit")
    @ApidocOperation(description = "新增融资额度", operationId = "/ticket/ticketfinance/addFinanceCredit")
    @ApidocReturnR
    public Result addFinanceCredit(@ApidocParam(name = "", required = true) @Validated @RequestBody SupplierCreditAddDto supplierCreditAddDto) {
        try {
            supplierCreditService.addFinanceCredit(supplierCreditAddDto, this.getUser());
            return Result.ok();
        } catch (SysException e) {
            return Result.error(e.getMsg());
        }
    }

    @PutMapping("/updateFinanceCredit")
    @ApidocOperation(description = "修改融资授信", operationId = "/ticket/ticketfinance/updateFinanceCredit")
    @ApidocReturnR
    public Result updateFinanceCredit(@ApidocParam(name = "", required = true) @Validated @RequestBody SupplierCreditUpdateDto supplierCreditUpdateDto) {
        try {
            supplierCreditService.updateFinanceCredit(supplierCreditUpdateDto, this.getUser());
            return Result.ok();
        } catch (SysException e) {
            return Result.error(e.getMsg());
        }
    }

    @GetMapping("/list")
    @ApidocOperation(description = "融资额度列表", operationId = "list/1")
    @ApidocReturnPage(genericTypeClass = SupplierCreditListDto.class)
    public Result list(@ApidocParamsPage(name = "params", keyName = {
            "creditNo 额度编号",
            "enterpriseName 授信额度主体",
            "financeInstitutyId 金融机构",
            "creditStatus 授信状态，全部时，不传入值"
    }) @RequestParam Map<String, Object> params) {
        params.put("enterpriseId", this.getUser().getEnterpriseId());
        PageUtils page = supplierCreditService.querySupplierCreditPage(params, this.getUser(), this.getSession());
        return Result.ok().put("page", page);
    }

    @GetMapping("/getFinanceCredit/{id}")
    @ApidocOperation(description = "融资额度详情", operationId = "getFinanceCredit")
    @ApidocReturnR(otherkv = {
            @ApidocResultKeyValR(resultType = ResultTypeInR.TYPE_OBJECT, key = "data", valueClass = SupplierCreditDetailDto.class)
    })
    public Result getFinanceCredit(@ApidocParam(name = "融资额度id", required = true) @PathVariable("id") String id) {
        return Result.ok().put("data", supplierCreditService.getFinanceCredit(id));
    }


}
